package com.xianyu.us.common.utils;

import java.util.Random;


import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.xianyu.us.common.exception.ServiceException;

/**
 * 通过接口发送信息
 * @author wangshili
 *
 */

public class SendMsgUtils {
	/**
	 * 发送短信工具类
	 * @param phone 目标电话号码
	 */
	 public static String sendPhone(String phone) {
		//发送短信模板，可以直接在官网生成
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
				"LTAI4Fy3mhMV8Bvrz3wbXhrh",  
				"zX3KgIYBbzZPDou1TDdgEaD5nub5bX"); 
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");//可以不设置
        request.putQueryParameter("PhoneNumbers", phone); //要发送的号码
        request.putQueryParameter("SignName", "咸渔网"); //签名，要申请
        request.putQueryParameter("TemplateCode", "SMS_193510821"); //模板码要申请
        String rand = RandomNumberUtils.getString(6);//获取6位的随机数
        request.putQueryParameter("TemplateParam", "{'code':'"+rand+"'}");//
        //要往账号里充点钱才能发送，不然 会显示余额不足，充1块也行，短信是要
        try {
            CommonResponse response = client.getCommonResponse(request);//执行
            String data = response.getData();
            System.out.println(response.getData());//打印结果数据=
            if(data.indexOf("OK")==-1)
            	throw new ServiceException("发送失败，请重试");

            return rand;//将验证码返回
            
        } catch (ServerException e) {
            e.printStackTrace();
            return null;
        } catch (ClientException e) {
            e.printStackTrace();
            return null;
        }
	}
	

	/**
	 * 发送邮件工具类
	 * @param mail 邮件名
	 * @return
	 */
	public static String sendMail(JavaMailSender mailSender,String mail) {//toSend需要发送的邮箱
		try {
			SimpleMailMessage sMail = new SimpleMailMessage();//获取发送模板
			String rand = RandomNumberUtils.getString(6);//获取6位验证码
			sMail.setSubject("闲渔验证码");//邮件名
			sMail.setText("您本次注册的验证码为："+rand);
			sMail.setTo(mail);//收件人
			sMail.setFrom("980841773@qq.com");//发件人
			mailSender.send(sMail);//发送
			return rand;//将随机码返回，便于缓存
		} catch (Exception e) {
			throw new ServiceException("发送失败,请检查输入的邮箱号是否正确");
		}

	}

}
